package com.mooral.web.tracker;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Iterator;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.DynaActionForm;

import com.mooral.bean.User;
import com.mooral.context.Context;
import com.mooral.context.ContextSession;
import com.mooral.dataAccess.DataAccessConnection;

public class Tracker {

	public static void SaveAction(String from, String to, ActionForm form, String ip) throws Exception {
		
		Context context = ContextSession.getCurrentContext();
		User user = (User) context.getUser();
		String userId = (user == null ? "0" : user.get("id").toString());
		DynaActionForm dform = (DynaActionForm) form;
		String data = "";
		
		if(dform != null)
		{
			Iterator iterator = dform.getMap().keySet().iterator();
			while(iterator.hasNext())
			{
				Object object = iterator.next(); 
				if( object != null)
					data += (data == "" ? "" : "|") + object.toString() + " = " + dform.get(object.toString());
			}
		}
		
		DataAccessConnection dataAccessConnection = context.getDataAccessConnection();
			
		dataAccessConnection.executeUpdate("insert into tracking (user_id,`from`,`to`, data, ip, created) values (" + userId + ",'" + from + "','" + to + "','" + data + "','" + ip + "','" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Timestamp(System.currentTimeMillis())) + "')");
		
		// TODO QUE HACER CUANDO SE INSERTA Y QUE HACER CUANDO NO
		
		dataAccessConnection.disposeConnection();
	}

}
